package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.bean.UserRegisterRequest;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.email.EmailCheckUtils;
import org.chen.wordwave.tools.email.EmailUtil;
import org.chen.wordwave.tools.md5.MD5Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Register extends BaseActivity {
    private boolean isUsernameAvailable = false;
    private boolean isEmailAvailable = false;
    private static final int GET_MESSAGE_CODE = 1;
    private ImageView iv_goback;
    private EditText et_email,et_yanzhengma,et_one_pwd,et_sure_pwd,et_userName;
    private Button btn_get_yanzhengma,btn_register;
    private TextView tv_xieyi,tv_title,tv_privacy;
    private int nowSecond = 60;
    private boolean isGetMessageCode=false;
    private String email,userName;
    private ToastParams params = new ToastParams();
    private ApiService apiService;
    private ProgressDialog progressDialog;
    private Handler handler=new Handler(Looper.getMainLooper()){
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {

            if (msg.what == GET_MESSAGE_CODE) {
                if (nowSecond != 0) {
                    btn_get_yanzhengma.setEnabled(false);
                    btn_get_yanzhengma.setText(nowSecond + "s");
                    nowSecond--;
                    handler.sendEmptyMessageDelayed(GET_MESSAGE_CODE, 1000);
                } else {
                    btn_get_yanzhengma.setEnabled(true);
                    btn_get_yanzhengma.setText(R.string.again);
                    nowSecond = 60;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        apiService = ApiClient.getClient(getApplicationContext()).create(ApiService.class);
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.register_act;
    }

    @Override
    public void init() {
        et_email = findViewById(R.id.et_email);
        iv_goback = findViewById(R.id.iv_goback);
        et_yanzhengma = findViewById(R.id.et_yanzhengma);
        btn_get_yanzhengma = findViewById(R.id.btn_get_yanzhengma);
        et_one_pwd = findViewById(R.id.et_one_pwd);
        et_sure_pwd = findViewById(R.id.et_sure_pwd);
        tv_xieyi = findViewById(R.id.tv_xieyi);
        btn_register = findViewById(R.id.btn_register);
        tv_title = findViewById(R.id.tv_title);
        et_userName = findViewById(R.id.et_userName);
        tv_privacy = findViewById(R.id.tv_privacy);
        tv_title.setText(R.string.register);
        et_userName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    checkUserNameExists(et_userName.getText().toString().trim());
                }
            }
        });

        et_email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    checkEmailExists(et_email.getText().toString().trim());
                }
            }
        });
//        返回点击事件
        iv_goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        点击获取验证码
        btn_get_yanzhengma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_yanzhengma.setError(null);
                if (checkEmail()){
                    return;
                }

                email = et_email.getText().toString().trim();
                userName = et_userName.getText().toString().trim();

                EmailUtil.sendEmail(getApplicationContext(),email);
                handler.sendEmptyMessage(GET_MESSAGE_CODE);
//                设置获取过验证码
                isGetMessageCode=true;

            }
        });


        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog();
//                先取消所有错误信息
                setNoErrorMessage();

                String userName = et_userName.getText().toString().trim();

                if (userName.isEmpty()){
                    et_userName.setError(getString(R.string.userName_is_null));
                    dismissProgressDialog();
                    return;
                }

                if (!isGetMessageCode){
//                    说明没有点击获取验证码
                    et_yanzhengma.setError(getString(R.string.pleass_code));
                    dismissProgressDialog();
                    return;
                }

                if (checkEmail()){
                    dismissProgressDialog();
                    return;
                }

                String pwd1= et_one_pwd.getText().toString().trim();
                String pwd2=et_sure_pwd.getText().toString().trim();

                if (pwd1.isEmpty()){
                    et_one_pwd.setError(getString(R.string.pws_not_null));
                    dismissProgressDialog();
                    return;
                }
                if (pwd2.isEmpty()){
                    et_sure_pwd.setError(getString(R.string.pws2_not_null));
                    dismissProgressDialog();
                    return;
                }
                et_sure_pwd.setError(null);
                if (!pwd1.equals(pwd2)){
//                    说明两次密码不一致
                    et_sure_pwd.setError(getString(R.string.pws_pws2_not_simple));
                    dismissProgressDialog();
                    return;
                }

                if (!isUsernameAvailable || !isEmailAvailable) {
                    params.text = getString(R.string.email_or_account_exits);
                    params.style = new CustomToastStyle(R.layout.error);
                    Toaster.show(params);
                    dismissProgressDialog();
                    return;
                }

                String code = EmailUtil.getCode();

//                拿到手机号和密码进行注册
                if (!et_yanzhengma.getText().toString().trim().isEmpty() && code.equals(et_yanzhengma.getText().toString().trim())){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
                    UserRegisterRequest userRegisterRequest = new UserRegisterRequest(userName,email,MD5Utils.MD5Encode(pwd1,null),simpleDateFormat.format(new Date()));
                    UserInfo userInfo = new UserInfo(email,simpleDateFormat.format(new Date()), MD5Utils.MD5Encode(pwd1,null),userName);
                    apiService.register(userRegisterRequest).enqueue(new Callback<UserRegisterRequest>() {
                        @Override
                        public void onResponse(@NonNull Call<UserRegisterRequest> call, @NonNull Response<UserRegisterRequest> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                boolean save = userInfo.save();
                                if (save){
                                    WordInit.userInfo = userInfo;
                                    WordInit.flyerEditor.putString("email",userInfo.getEmail());
                                    WordInit.flyerEditor.putString("account",userInfo.getAccount());
                                    WordInit.flyerEditor.putString("registerTime",userInfo.getRegisterTime());
                                    WordInit.flyerEditor.commit();
                                    ToastParams toastParams = new ToastParams();
                                    toastParams.style = new CustomToastStyle(R.layout.success);
                                    toastParams.text = getString(R.string.register_success);
                                    Toaster.show(toastParams);
                                    dismissProgressDialog();
                                    startActivity(new Intent(Register.this, Main.class));
                                }else {
                                    params.text = getString(R.string.register_fail);
                                    params.style = new CustomToastStyle(R.layout.error);
                                    Toaster.show(params);
                                    dismissProgressDialog();
                                }
                            } else {
                                params.text = getString(R.string.register_fail);
                                params.style = new CustomToastStyle(R.layout.error);
                                Toaster.show(params);
                                dismissProgressDialog();
                            }
                        }

                        @Override
                        public void onFailure(@NonNull Call<UserRegisterRequest> call,@NonNull Throwable t) {
                            params.text = getString(R.string.register_fail);
                            params.style = new CustomToastStyle(R.layout.error);
                            Toaster.show(params);
                            dismissProgressDialog();
                        }
                    });
                }else {
                    et_yanzhengma.setError(getString(R.string.code_fail));
                    params.text = getString(R.string.code_fail);
                    params.style = new CustomToastStyle(R.layout.error);
                    Toaster.show(params);
                    dismissProgressDialog();
                }

            }
        });


        tv_xieyi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Register.this,User.class);
                startActivity(intent);
            }
        });

        tv_privacy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Register.this,Privacy.class);
                startActivity(intent);
            }
        });

    }
    private void checkUserNameExists(String userName) {
        // 发送网络请求检查用户名是否存在
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setAccount(userName);
        apiService.registerUserInfo(userRegisterRequest).enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call,@NonNull Response<String> response) {
                if (response.isSuccessful() && response.body() != null) {
                    String body = response.body();
                    if (body.equals("400")) {
                        et_userName.setError(null);
                        isUsernameAvailable = true;
                    } else {
                        params.text = getString(R.string.account_exits);
                        params.style = new CustomToastStyle(R.layout.error);
                        Toaster.show(params);
                        et_userName.setError(getString(R.string.account_exits));
                        isUsernameAvailable = false;
                    }
                }else {
                    showNetworkError();
                    isUsernameAvailable = false;
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call,@NonNull Throwable t) {
                showNetworkError();
                isUsernameAvailable = false;
            }
        });
    }
    private void showNetworkError() {
        params.text = getString(R.string.network_error);
        params.style = new CustomToastStyle(R.layout.error);
        Toaster.show(params);
    }
    private void checkEmailExists(String email) {
        // 发送网络请求检查邮箱是否存在
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        apiService.registerUserInfoByEmail(userRegisterRequest).enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call,@NonNull Response<String> response) {
                if (response.isSuccessful() && response.body() != null) {
                    String body = response.body();
                    if (body.equals("400")) {
                        et_email.setError(null);
                        isEmailAvailable = true;
                    } else {
                        params.text = getString(R.string.email_exits);
                        params.style = new CustomToastStyle(R.layout.error);
                        Toaster.show(params);
                        et_email.setError(getString(R.string.email_exits));
                        isEmailAvailable = false;
                    }
                }else {
                    showNetworkError();
                    isEmailAvailable = false;
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call,@NonNull Throwable t) {
                showNetworkError();
                isEmailAvailable = false;
            }
        });
    }
    private void setNoErrorMessage() {
        et_email.setError(null);
        et_one_pwd.setError(null);
        et_sure_pwd.setError(null);
        et_yanzhengma.setError(null);
        et_userName.setError(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeMessages(GET_MESSAGE_CODE);
    }

    private boolean checkEmail(){
        email=et_email.getText().toString().trim();
        if (email.isEmpty()){
            et_email.setError(getString(R.string.pleass_in_phone));
            return true;
        }
        if (EmailCheckUtils.isEmailLegal(email)){
            et_email.setError(getString(R.string.phone_not_vaild));
            return true;
        }
        return false;
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(getString(R.string.uploading));
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
